package com.budwk.app.base.utils;

import com.alibaba.fastjson.JSONObject;
import com.budwk.app.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.IOUtils;
import org.nutz.mvc.upload.TempFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class PoiTlUtil {

    public static Sheet getBookSheet(TempFile file) {
        try {
            IOUtils.setByteArrayMaxOverride(2000000000);
            Workbook book = WorkbookFactory.create(file.getInputStream()); //创建工作簿
            Sheet sheet = book.getSheetAt(0);//获取到工作表
            int lastRowNum = sheet.getLastRowNum();//获取到表格最后一行
            if (lastRowNum < 1 ) {
                throw new AppException("你未导入任何数据，请添加数据后导入...");
            }
            return sheet;
        } catch (IOException e) {
            log.error("poiUtil getBookSheet error: ", e);
            throw new AppException("获取单元格失败!");
        }
    }

    /**
     * 获取所有导入的数据json存储
     * @param sheet 单元格
     * @param startRow 数据起始行
     */
    public static List<JSONObject> getImportContent(Sheet sheet, int startRow) {
        List<JSONObject> results = new ArrayList<>();
        // 获取所有行的标题字段
        List<String> importFields = getImportFields(sheet);
        // 获取表格数据
        for (int rowIndex = startRow; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
            JSONObject jsonObject = new JSONObject();
            Row row = sheet.getRow(rowIndex);
            for (int i = 0; i < importFields.size(); i++) {
                Cell cell = row.getCell(i);
                String value = new DataFormatter().formatCellValue(cell);
                jsonObject.put(importFields.get(i), value);
            }
            results.add(jsonObject);
        }
        return results;
    }

    /**
     * 获取导入数据的所有字段，并转为驼峰存储 如 user_id  -> userId
     * @param sheet
     * @return
     */
    public static List<String> getImportFields(Sheet sheet) {
        Row row = sheet.getRow(1);
        int cellIndex = 0;
        List<String> list = new ArrayList<>();
        while (true) {
            Cell cell = row.getCell(cellIndex);
            if (cell == null) {
                break;
            }
            String value = cell.getStringCellValue();
            if (StringUtils.isEmpty(value)) {
                break;
            }
            // 转为下划线驼峰
            String str = StrUtil.lineToHump(value);
            list.add(str);
            cellIndex ++;
        }
        return list;
    }
}
